import store from "@/store";
import { showLoading, hideLoading } from "@/utils";
import urlConfig from "@/request/urlConfig.js"; // 引入地址配置
import * as permissionCheck from '@/chronicDisease/utils/permissionCheck.js'
let uploadTimer = null;

// 图片上传地址   
const uploadUrl = urlConfig.baseURL + "/user/uploads/public/uploadImage";
// toast弹框,需要定时器防止跟hideLoading冲突
const toast = (title) => {
	uploadTimer && clearTimeout(uploadTimer); // 每次调用之前清除定时器
	uploadTimer = setTimeout(() => {
		uni.showToast({
			title,
			icon: "none",
			mask: false,
		});
	}, 10);
};

// 单张选择上传图片
export function uploadImage() {
	return new Promise((resolve) => {
		permissionCheck.premissionCheckWrap('CAMERA_EXTERNAL_STORAGE').then(() => {
			uni.chooseImage({
				count: 1,
				sizeType: ["original", "compressed"],
				sourceType: ["album", "camera"],
				success: async (info) => {
					const tempFilePaths = info.tempFilePaths || [];
					const uploadUrl = await uploadFile(tempFilePaths[0]);
					resolve(uploadUrl);
				},
			});
		})

	});
}

// 上传文件
export function uploadFile(
	filePath,
	text = "图片",
	loading = true,
	loadingText
) {
	return new Promise((resolve) => {
		loading && showLoading(loadingText || `${text}上传中...`, 20000);
		uni.uploadFile({
			url: uploadUrl,
			filePath: filePath,
			// #ifdef H5 || APP-PLUS
			timeout: 20000,
			// #endif
			name: "file",
			header: {
				userAccessToken: uni.getStorageSync("token") || "",
			},
			success: (res) => {
				hideLoading(0);
				if (res.statusCode !== 200) return toast(`${text}上传失败，请重试`);
				const result = JSON.parse(res.data);
				if (![200, "200"].includes(result.code)) {
					return toast(result.msg || `${text}上传失败，请重试`);
				}
				console.log(`${text}上传结果`, result);
				resolve(result.data?.uploadUrl || "");
			},
			fail: (err) => {
				hideLoading(0);
				if (err.errMsg.includes("timeout")) {
					toast(`${text}上传超时，请重试`);
					console.log(`${text}上传超时`, err);
				} else {
					toast(`${text}上传失败，请重试`);
					console.log(`${text}上传失败`, err);
				}
			},
		});
	});
}
